<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="户主姓名" prop="s_holder_username">
          <el-input v-model="queryParams.s_holder_username" placeholder="户主姓名" clearable />
        </el-form-item>
        <el-form-item label="身份证号码" prop="s_holder_id_card_no">
          <el-input v-model="queryParams.s_holder_id_card_no" placeholder="户主身份证号码" clearable />
        </el-form-item>
        <el-form-item label="手机号" prop="s_holder_tel">
          <el-input v-model="queryParams.s_holder_tel" placeholder="户主手机号" clearable />
        </el-form-item>
        <el-form-item label="片区" prop="area_id">
          <el-select v-model="queryParams.area_id" placeholder="全部" clearable class="!w-[180px]">
            <el-option v-for="item in areaList" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="s_address">
          <el-input v-model="queryParams.s_address" placeholder="详细地址" clearable />
        </el-form-item>
        <el-form-item label="水表编号" prop="s_code">
          <el-input v-model="queryParams.s_code" placeholder="水表编号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery()">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery()">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="flex-x-between mb-10px">
        <div>
          <el-button v-hasPerm="['/admin/water/waterMeter/add']" type="success" icon="plus" @click="handleOpenDialog()">
            新增
          </el-button>
          <el-button :disabled="selectIds.length === 0" v-hasPerm="'/admin/water/waterMeter/del'" type="danger"
            icon="delete" @click="handleDelete()">
            删除
          </el-button>
        </div>
      </div>
      <el-table ref="dataTableRef" v-loading="loading" :data="pageData" highlight-current-row
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="户头id" prop="id" width="80" />
        <el-table-column label="水表编号" prop="code" width="100" />
        <el-table-column label="户主姓名" prop="holder_username" width="120" />
        <!-- <el-table-column label="户主身份证" prop="holder_id_card_no" min-width="170" /> -->
        <el-table-column label="户主电话" prop="holder_tel" min-width="120" />
        <el-table-column label="当月是否已抄表" width="150">
          <template #default="scope">
            {{ scope.row.reported_current_month == 1 ? '已抄表' : '未抄表' }}
          </template>
        </el-table-column>
        <el-table-column label="收水规则" prop="balance" min-width="190">
          <template #default="scope">
            <span>{{ scope.row?.charge_rule?.name }},</span>
            <span>{{ scope.row?.charge_rule?.charge_mode == 1 ? '统一定价' : '阶梯收费' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="片区名称" prop="area.name" min-width="160" />
        <el-table-column label="详细地址" prop="address" min-width="300" />
        <el-table-column label="当前读数" prop="water_number" min-width="140" />
        <el-table-column label="可用储值、余额" prop="balance" min-width="140" />
        <el-table-column align="center" fixed="right" label="操作" width="300">
          <template #default="scope">
            <el-button v-hasPerm="'accountAdmin:qrCode'" type="primary" size="small" link icon="Document"
              @click="handleQrCode(scope.row)">
              二维码
            </el-button>
            <el-button v-hasPerm="'/admin/water/waterMeterBalanceLog/pageList'" type="primary" size="small" link
              icon="Document" @click="handleOpenList(scope.row)">
              余额明细
            </el-button>
            <el-button v-hasPerm="'/admin/water/waterMeter/update'" type="primary" size="small" link icon="edit"
              @click="handleOpenDialog(scope.row)">
              修改
            </el-button>
            <el-button v-hasPerm="'/admin/water/waterMeter/del'" type="danger" icon="delete" link size="small"
              @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page" v-model:limit="queryParams.ps"
        @pagination="handleQuery()" />
    </el-card>

    <!-- 用户表单 -->
    <el-dialog :close-on-click-modal="false" v-model="dialog.visible" :title="dialog.title" append-to-body
      @close="handleCloseDialog">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="户主姓名" prop="holder_username">
          <el-input v-model="formData.holder_username" placeholder="请输入户主姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="holder_tel">
          <el-input v-model="formData.holder_tel" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="身份证号码" prop="holder_id_card_no">
          <el-input v-model="formData.holder_id_card_no" placeholder="请输入户主身份证号码" />
        </el-form-item>
        <el-form-item label="片区" prop="area_id">
          <el-select v-model="formData.area_id" placeholder="全部" clearable class="!w-[100%]">
            <el-option v-for="item in areaList" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入具体地址，精确到门牌号" />
        </el-form-item>
        <el-form-item label="收费规则" prop="charge_rule_id">
          <el-select v-model="formData.charge_rule_id" placeholder="全部" clearable class="!w-[100%]">
            <el-option v-for="item in ruleList" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="初始读数" prop="water_number">
          <el-input v-model="formData.water_number" placeholder="请输入初始读数" />
        </el-form-item>
        <el-form-item label="储值" prop="balance">
          <el-input v-model="formData.balance" placeholder="请输入储值" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input resize="none" show-word-limit v-model="formData.remark" type="textarea" maxlength="200"
            placeholder="请输入备注" />
        </el-form-item>

      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" v-model="listShow" title="余额明细" append-to-body width="60%"
      @close="handleCloseList">

      <el-form ref="listFormRef" :model="listPage" :inline="true">
        <el-form-item label="月份" prop="month">
          <el-date-picker v-model="listPage.month" value-format="YYYYMM" format="YYYY-MM" type="month"
            placeholder="月份" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleOpenList()">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetList()">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <el-table ref="dataTableRef" :data="logList" highlight-current-row>
        <el-table-column label="月份" prop="month" width="100" />
        <el-table-column label="变动前余额" prop="old_amount" width="100" />
        <el-table-column label="变动金额" prop="change_amount" width="120" />
        <el-table-column label="文字说明" prop="title" />
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            <span v-if="scope.row.created_at > 0">
              {{ formatTimestamp(scope.row.created_at * 1000) }}
            </span>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-if="listTotal > 0" v-model:total="listTotal" v-model:page="listPage.page"
        v-model:limit="listPage.ps" @pagination="handleOpenList()" />
    </el-dialog>

    <el-dialog :close-on-click-modal="false" v-model="Qrcodeishow" width="432px" title="二维码">
      <div ref="card" class="p-3 text-[18px] pt-8 w-[400px] h-[600px] font-600">
        <div class="flex mb-8">
          <div class="w-[60px] shrink-0">姓名：</div>
          <div class="border-b-black border-b flex-1">{{ rowData?.holder_username }}</div>
        </div>
        <div class="flex mb-8">
          <div class="w-[60px] shrink-0">地址：</div>
          <div class="border-b-black border-b flex-1">{{ rowData?.address }}</div>
        </div>
        <div class="flex mb-8">
          <div class="w-[60px] shrink-0">片区：</div>
          <div class="border-b-black border-b flex-1">{{ rowData?.area?.name }}</div>
        </div>
        <div class="flex mb-8">
          <div class="w-[60px] shrink-0">编号：</div>
          <div class="border-b-black border-b flex-1">{{ rowData?.code }}</div>
        </div>
        <div class="flex justify-center pt-16">
          <div class="border-b-black border p-2 border-r h-[180px]">
            <QRCode ref="qrcode" :value="qrValue" :size="160" />
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="qrcodeLoading" type="primary" @click="handleSubmitQrCode">下 载</el-button>
          <el-button @click="handleCloseQrCode">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "AccountAdmin",
  inheritAttrs: false,
});


import accountAPI, { Form, PageVO, accountPageQuery } from "@/api/waterMeter/accountAdmin";
import areaAPI from "@/api/waterMeter/area";
import chargeRuleAPI from "@/api/waterMeter/chargeRule";
import { formatTimestamp } from '@/utils/index';
import html2canvas from "html2canvas";
import QRCode from 'qrcode.vue';

const queryFormRef = ref(ElForm);
const pageData = ref<PageVO[]>([]);
const formRef = ref(ElForm);
const loading = ref(false);
const total = ref(0);
const listShow = ref(false);
const logList = ref<any>([]);
const listTotal = ref<number>(0);
const listFormRef = ref(ElForm);
const listPage = reactive<any>({
  page: 1,
  ps: 10,

})

const Qrcodeishow = ref(false);
const card = ref<HTMLDivElement | null>(null)
const rowData = ref<any>({});
const qrValue = ref<string>('');  // 二维码的内容
const qrcodeLoading = ref(false);




// 他开code
const handleQrCode = (row: any) => {
  rowData.value = row;
  Qrcodeishow.value = true;
  accountAPI.getMultiGet({
    codes: 'meter_info_qrcode_prefix'
  }).then((res: any) => {
    qrValue.value = res.lists.meter_info_qrcode_prefix + `?water_meter_id=${row.id}&water_meter_code=${row.code}`;
  })
}

// 下载二维码
const handleSubmitQrCode = () => {
  qrcodeLoading.value = true;
  if (card.value) {
    html2canvas(card.value).then((canvas) => {
      // 将canvas转化为图片并下载
      const link = document.createElement('a')
      link.href = canvas.toDataURL('image/png')
      link.download = `${rowData.value.holder_username}-${Date.now()}.png`
      link.click()
      qrcodeLoading.value = false;
    })
  }
}

// 关闭弹窗
const handleCloseQrCode = () => {
  Qrcodeishow.value = false;
}

// 打开余额弹窗
const handleOpenList = (row?: any) => {
  accountAPI.getBalanceLogPage({
    ...listPage,
    water_meter_code: row?.code
  }
  ).then((res: any) => {
    logList.value = res.data;
    listTotal.value = res.total;
  })

  listShow.value = true;
}

// 关闭弹窗
const handleCloseList = () => {
  listShow.value = false;
  listFormRef.value.resetFields();
  listFormRef.value.clearValidate();
  logList.value = [];
}

// 重置
const handleResetList = () => {
  listFormRef.value.resetFields();
  listFormRef.value.clearValidate();
}

const queryParams = reactive<accountPageQuery>({
  page: 1,
  ps: 10,
});

const dialog = reactive({
  visible: false,
  title: "新增户头",
});

// 选中的ID
const selectIds = ref<number[]>([]);

const formData = reactive<Form>({
  holder_username: "",
  holder_id_card_no: "",
  holder_tel: "",
  area_id: "",
  address: "",
  water_number: "0",
  balance: "0",
  charge_rule_id: "",
  remark: ""
});

const rules = reactive({
  holder_username: [{ required: true, message: "请输入户主姓名", trigger: "blur" }],
  // holder_id_card_no: [{ required: true, message: "请输入户主身份证号码", trigger: "blur" }],
  // holder_tel: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  area_id: [{ required: true, message: "请选择片区", trigger: ["blue", "change"] }],
  // address: [{ required: true, message: "请输入地址", trigger: "blur" }],
  water_number: [{ required: true, message: "请输入初始读数", trigger: "blur" }],
  balance: [{ required: true, message: "请输入储值", trigger: "blur" }],
  charge_rule_id: [{ required: true, message: "请选择收费规则", trigger: ["blue", "change"] }]
});

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
const areaList = ref<any>([]);
const ruleList = ref<any>([]);
async function handleOpenDialog(data?: any) {
  dialog.visible = true;
  areaList.value = (await areaAPI.getPage()).list;
  ruleList.value = (await chargeRuleAPI.getPage()).list;
  console.log(ruleList.value)
  if (data) {
    Object.assign(formData, { ...data });
    dialog.title = "修改户头";
  } else {
    dialog.title = "新增户头";
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  formRef.value.resetFields();
  formRef.value.clearValidate();

  formData.id = undefined;
}


// 提交表单（防抖）
const handleSubmit = useDebounceFn(() => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      if (formData.id) {
        accountAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        accountAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);


// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

/**
 * 删除用户
 *
 * @param id  用户ID
 */
function handleDelete(id?: number) {
  let userIds = id ? [id] : selectIds.value;
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      accountAPI.deleteByIds({ ids: userIds })
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

/** 查询通知公告 */
function handleQuery() {
  loading.value = true;
  accountAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.data;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置通知公告查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.page = 1;
  handleQuery();
}

onMounted(async () => {
  areaList.value = (await areaAPI.getPage()).list;
  handleQuery();
});
</script>
